
_ = require 'underscore'
fsp = require '../bin/libs/fs-promises'
Q = require 'q'
path = require 'path'
user = require '../db/User'
crypto = require 'crypto'

module.exports= (app)->

  ITERATOR_COUNT = 1024 #迭代循环1024次
  PASSWORD_LENGTH = 32  #密码的位数
  SALT_LENGTH = 8 #盐值位数
  SALT_COOKIE = "remember_me&&!!" #cookie验证


  #生成密文，默认HMAC函数是sha1算法
  _encrypt = (txt, salt, cb) ->
    txt = txt || ""
    txt = txt.toString()
    crypto.randomBytes SALT_LENGTH, (err, result) ->
      cb err if err
      salt = salt || result.toString('hex')
      crypto.pbkdf2 txt, salt, ITERATOR_COUNT, PASSWORD_LENGTH, (err, hash) ->
        cb err, hash.toString('hex'), salt

  #生成密文，默认HMAC函数是sha1算法
  _signedCookies = (txt, salt, cb) ->
    txt = txt || ""
    txt = txt.toString()
    crypto.pbkdf2 txt, salt, 1024, 8, (err, hash) ->
      cb err, hash.toString('hex'), salt

  #管理员首页
  app.get '/admin/index', (req, res, next) ->
    res.render 'admin/index', {layout: false, username: req.session.user.username}

  # 管理员登录－－填写信息页面
  app.get '/admin/login', (req, res, next) ->
    return res.redirect '/admin/index' if req.session and req.session.user and  req.session.user.role == 'admin'
    res.render 'admin/login-admin', {layout: false,  showTitle: "我是管理登录页面", noLogin: true}

  #管理员退出登录
  app.get '/admin/logout', (req, res, next) ->
    req.session.user = null
    res.redirect '/adlogin'

  #超级管理员登录
  app.post '/admin/login', (req, res, next) ->
    user_data = _.pick(req.body, ['username', 'password'])
    # 必须保证密码不能为空
    user_data.password = user_data.password || ""
    new Promise (resolve, reject) ->
      user.findOne {username: user_data.username, role: "admin"}, (err, data) ->
        return reject('登录失败') if err
        return reject('用户名不存在') if !data
        resolve(data)
    .then (data) ->
      new Promise (resolve, reject) ->
        _encrypt user_data.password, data.salt, (err, hash, salt) ->
          return reject('登录失败') if err
          return reject('密码错误') if hash != data.password
          resolve(data)
    .then (data) ->
      user_json =  _.pick(data, ['username', 'role', 'photo'])
      req.session.user = user_json
      # res.redirect '/'
      res.status(200).json {code: 0, message:"登录成功", data: user_json}
    .catch (err) ->
      res.status(200).json {code:-1, message: err}
